package com.aioz.security.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.aioz.security.common.ResponseResult;
import com.aioz.security.entity.*;
import com.aioz.security.entity.dto.PositionDto;
import com.aioz.security.mapper.*;
import com.aioz.security.service.PositionService;
import com.aioz.security.utils.RedisCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Aioz
 * @since 2022-09-27
 */
@Service
@Slf4j
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements PositionService {

    private static final int PAGE_SIZE = 4;

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private TechnologyMapper technologyMapper;

    @Resource
    private CompanyInfoMapper companyInfoMapper;

    @Resource
    private RedisCache redisCache;

    @Override
    public ResponseResult getPositionByCompanyId(Integer companyId,Integer currentPage) {
        long startTime = System.currentTimeMillis();
        List<PositionDto> positions = positionMapper.getPositionByCompanyId(companyId);
        int size = positions.size();
        positions = positions.stream()
                        .skip(currentPage * PAGE_SIZE - PAGE_SIZE)
                        .limit(PAGE_SIZE)
                        .collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("positions",positions);
        map.put("size",size);
        long endTime = System.currentTimeMillis();
        //打印
        log.info("程序运行时间{} ms" ,(endTime - startTime));
        return new ResponseResult(200,map);
    }

    @Override
    public ResponseResult likePosition(Integer id) {
        ////获取当前登录用户
        //Long userId = getCurrentUserId();
        ////判断用户是否浏览过此岗位（redis 的set集合）
        //String key = "position:liked:" + id;
        //boolean isMember = redisCache.isMember(key, userId.toString());
        //if(BooleanUtils.isFalse(isMember)){
        //    //没有，更新此职位浏览量 + 1
        //    boolean isSuccess = update().setSql("hits = hits + 1").eq("id", id).update();
        //    //保存当前登录用户到 redis 的set集合
        //    if(isSuccess){
        //        redisCache.setCacheSet(key, userId.toString());
        //    }
        //}
        //返回岗位详细信息给用户
        Map<String, Object> map = new HashMap<>();
        Position position = positionMapper.selectById(id);
        Company company = companyMapper.selectById(position.getCompanyId());
        QueryWrapper<CompanyInfo> companyInfoWrapper = new QueryWrapper<>();
        companyInfoWrapper.eq("company_id",position.getCompanyId());
        CompanyInfo companyInfo = companyInfoMapper.selectOne(companyInfoWrapper);
        QueryWrapper<Technology> technologyWrapper = new QueryWrapper<>();
        technologyWrapper.eq("category_id",position.getCategoryId());
        List<Technology> technologies = technologyMapper.selectList(technologyWrapper);
        List<String> technologyList = technologies.stream()
                        .map(Technology::getTechnology)
                        .collect(Collectors.toList());
        PositionDto position2 = positionMapper.getPositionDtoById(id);
        map.put("position",position2);
        map.put("company",company);
        map.put("companyInfo",companyInfo);
        map.put("technologies",technologyList);
        return new ResponseResult(200,map);
    }

    @Override
    public ResponseResult hotTopPosition(Integer currentPage) {
        List<PositionDto> hotPositions = positionMapper.getHotTopPosition();
        hotPositions = hotPositions.stream().skip((currentPage - 1) * 6L).limit(6).collect(Collectors.toList());
        return new ResponseResult(200,hotPositions);
    }

    @Override
    public ResponseResult likePositionByCategory(String category) {
        List<PositionDto> positions = positionMapper.likePositionByCategory(category);
        for (PositionDto position : positions) {
            QueryWrapper<Company> wrapper = new QueryWrapper<>();
            wrapper.eq("name",position.getCompany());
            position.setCompanyInfo(companyMapper.selectOne(wrapper));
        }
        return new ResponseResult<>(200,positions);
    }

    @Override
    public ResponseResult interestPosition(Integer positionId) {
        Long userId = getCurrentUserId();
        //判断用户是否关注过该职位
        if(1 == positionMapper.isUserInterest(positionId,userId)){
            return new ResponseResult<>(200,"您已关注过该职位");
        }else {
            boolean isInterest = positionMapper.userInterest(positionId, userId);
            System.out.println(isInterest);
            return new ResponseResult(200,"关注成功");
        }
    }

    @Override
    public ResponseResult getInterestPosition() {
        Long userId = getCurrentUserId();
        List<PositionDto> interestPositions = positionMapper.getInterestPositions(userId);
        return new ResponseResult<>(200,interestPositions);
    }

    @Override
    public ResponseResult likePositionByName(String name,Integer companyId) {
        log.info("查询 {} 有关岗位信息",name);
        List<PositionDto> positions = positionMapper.getPositionByCompanyId(companyId);
        positions = positions.stream()
                .filter(positionDto -> positionDto.getTitle().contains(name))
                .collect(Collectors.toList());
        //List<PositionDto> positions = positionMapper.likePositionByName(name);
        log.info("{}",positions);
        return new ResponseResult(200,positions);
    }

    @Override
    public ResponseResult addPosition(Position position) {
        position.setHrId(Math.toIntExact(getCurrentUserId()));
        position.setReleaseDate(LocalDateTime.now());
        positionMapper.insert(position);
        String msg = "岗位新增成功!";
        return new ResponseResult<>(200,msg);
    }

    @Override
    public ResponseResult stopRecruit(Integer positionId) {
        update().eq("id",positionId).setSql("state = 1").update();
        return new ResponseResult<>(200,"已停止招聘！");
    }

    @Override
    public ResponseResult updatePositionInfo(PositionDto positionDto) {
        Position position = getById(positionDto.getId());
        position.setTitle(positionDto.getTitle());
        position.setState(positionDto.getState());
        position.setEducation(positionDto.getEducation());
        position.setQuantity(positionDto.getQuantity());
        position.setSalaryDown(positionDto.getSalaryDown());
        position.setSalaryUp(positionDto.getSalaryUp());
        position.setCity(positionDto.getCity());
        position.setRequirement(positionDto.getRequirement());
        log.info("{}",position);
        boolean isSuccess = update().eq("id", position.getId()).update(position);
        if(isSuccess){
            return new ResponseResult<>(200,"岗位信息更新成功！");
        }
        return new ResponseResult<>(200,"系统繁忙，岗位信息更新失败！");
    }


    public Long getCurrentUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }
}
